<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" :label="$t('common.keywords')">
          <el-input
            v-model="queryParams.keywords"
            :placeholder="
              $t('visitor.name') +
              ', ' +
              $t('visitor.companyName') +
              ', ' +
              $t('visitor.email') +
              ', ' +
              $t('visitor.phone')
            "
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="opUserId" :label="$t('visitor.opName')">
          <el-autocomplete
            v-model="queryParams.opName"
            :fetch-suggestions="querySearch"
            clearable
            class="inline-input w-50"
            @select="handleSelect"
          />
        </el-form-item>
        <el-form-item prop="status" :label="$t('visitor.status')">
          <el-select
            v-model="queryParams.status"
            :placeholder="$t('common.choose')"
            :no-match-text="$t('common.choose')"
            style="width: 300px"
            @change="handleQuery"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">
            {{ $t("common.search") }}
          </el-button>
          <el-button icon="refresh" @click="handleResetQuery">{{ $t("common.reset") }}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="'visitor:add'" type="success" icon="plus" @click="handleOpenDialog()">
          {{ $t("common.add") }}
        </el-button>
      </div>

      <el-table ref="dataTableRef" v-loading="loading" :data="list" highlight-current-row stripe>
        <el-table-column :label="$t('visitor.name')" prop="name" />
        <el-table-column :label="$t('visitor.companyName')" prop="companyName" />
        <el-table-column :label="$t('visitor.email')" prop="email" />
        <el-table-column :label="$t('visitor.phone')" prop="phone" />
        <el-table-column :label="$t('visitor.status')" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 0" type="danger">
              {{ $t("visitor.statusOptions.0") }}
            </el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="success">
              {{ $t("visitor.statusOptions.1") }}
            </el-tag>
            <el-tag v-else type="danger">{{ $t("common.unknown") }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('visitor.opName')" align="center" prop="opName" />
        <el-table-column :label="$t('common.createdAt')" prop="createdAt">
          <template #default="scope">
            {{ dayjs(scope.row.createdAt).format("YYYY-MM-DD HH:mm:ss") }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.action')">
          <template #default="scope">
            <el-button
              v-hasPerm="'visitor:share'"
              type="primary"
              size="small"
              link
              icon="Share"
              @click="handleOpenShareDialog(scope.row.id)"
            >
              {{ $t("visitor.share") }}
            </el-button>
            <el-button
              v-hasPerm="'visitor:edit'"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              {{ $t("common.edit") }}
            </el-button>
            <el-button
              v-hasPerm="'visitor:delete'"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              {{ $t("common.delete") }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      :width="dialogWidth"
      @close="handleCloseDialog"
    >
      <el-form ref="iFormRef" :model="formData" :rules="rules">
        <el-form-item :label="$t('visitor.name')" prop="name">
          <el-input
            v-model="formData.name"
            :placeholder="$t('common.plsInput') + $t('visitor.name')"
          />
        </el-form-item>
        <el-form-item :label="$t('visitor.companyName')" prop="companyName">
          <el-input
            v-model="formData.companyName"
            :placeholder="$t('common.plsInput') + $t('visitor.companyName')"
          />
        </el-form-item>
        <el-form-item :label="$t('visitor.email')" prop="email">
          <el-input
            v-model="formData.email"
            :placeholder="$t('common.plsInput') + $t('visitor.email')"
          />
        </el-form-item>
        <el-form-item :label="$t('visitor.phone')" prop="phone">
          <el-input
            v-model="formData.phone"
            :placeholder="$t('common.plsInput') + $t('visitor.phone')"
          />
        </el-form-item>
        <el-form-item :label="$t('visitor.remark')" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :placeholder="$t('common.plsInput') + $t('visitor.remark')"
          />
        </el-form-item>
        <el-form-item :label="$t('visitor.status')" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="0">{{ $t("visitor.statusOptions.0") }}</el-radio>
            <el-radio :label="1">{{ $t("visitor.statusOptions.1") }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">{{ $t("common.confirm") }}</el-button>
          <el-button @click="handleCloseDialog">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="share_dialog.visible"
      :title="share_dialog.title"
      :width="dialogWidth"
      @close="handleCloseShareDialog"
    >
      <el-form ref="iShareFormRef" :model="share_formData" :rules="share_rules">
        <el-form-item :label-width="120" :label="$t('visitor.purpose')" prop="purposeId">
          <el-select
            v-model="share_formData.purposeId"
            :placeholder="$t('common.choose')"
            :no-match-text="$t('common.choose')"
            clearable
            class="!w-[100px]"
          >
            <el-option
              v-for="item in purposeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="120" :label="$t('visitor.dept')" prop="deptId">
          <el-select
            v-model="share_formData.deptId"
            :placeholder="$t('common.choose')"
            :no-match-text="$t('common.choose')"
            clearable
            class="!w-[100px]"
          >
            <el-option
              v-for="item in deptOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="120" :label="$t('visitor.planInAt')" prop="planInAt">
          <el-date-picker
            v-model="share_formData.planInAt"
            type="datetime"
            :placeholder="$t('common.choose') + $t('visitor.planInAt')"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item :label-width="120" :label="$t('visitor.planOutAt')" prop="planOutAt">
          <el-date-picker
            v-model="share_formData.planOutAt"
            type="datetime"
            :placeholder="$t('common.choose') + $t('visitor.planOutAt')"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmitShare">
            {{ $t("common.confirm") }}
          </el-button>
          <el-button @click="handleCloseShareDialog">{{ $t("common.cancel") }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import dayjs from "dayjs";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
defineOptions({
  name: "Visitors",
  inheritAttrs: false,
});

import VisitorApi, { IForm, IShareForm, IPageQuery, IPageVO } from "@/api/visitor/index";
import DeptAPI from "@/api/dept/index";
import VisitPurposeAPI from "@/api/visit_purpose/index";
import VisitorAPI from "@/api/visitor/index";
const screenWidth = window.innerWidth;
const dialogWidth = screenWidth < 768 ? "90%" : "500px";
const queryFormRef = ref(ElForm);
const iFormRef = ref(ElForm);
const iShareFormRef = ref(ElForm);
const purposeList = reactive<IPageVO[]>([]);

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<IPageQuery>({
  pageNum: 1,
  pageSize: 10,
  keywords: "",
  status: undefined,
  opUserId: undefined,
  opName: undefined,
});

const list = ref<IPageVO[]>();

const purposeOptions = ref<OptionType[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<IForm>({
  id: undefined,
  name: "",
  companyName: "",
  email: "",
  phone: "",
  remark: "",
  status: 1,
});

const rules = reactive({
  name: [{ required: true, message: t("common.plsInput") + t("visitor.name"), trigger: "blur" }],
  companyName: [
    { required: true, message: t("common.plsInput") + t("visitor.companyName"), trigger: "blur" },
  ],
  email: [
    { required: true, message: t("common.plsInput") + t("visitor.email"), trigger: "blur" },
    { email: true, message: t("common.plsInput") + t("visitor.rightEmail"), trigger: "blur" },
  ],
  phone: [{ required: true, message: t("common.plsChoose") + t("visitor.phone"), trigger: "blur" }],
});

const validateDateRange = (rule: any, value: any, callback: (arg0: Error | undefined) => void) => {
  if (!share_formData.planInAt || !share_formData.planOutAt) {
    callback(new Error(t("visitor.vistorDateRequired")));
  } else if (new Date(share_formData.planInAt) > new Date(share_formData.planOutAt)) {
    callback(new Error(t("visitor.planInAtMustLessThanPlanOutAt")));
  } else {
    callback(undefined);
  }
};

const share_rules = reactive({
  purposeId: [
    { required: true, message: t("common.plsChoose") + t("visitor.purpose"), trigger: "blur" },
  ],
  deptId: [{ required: true, message: t("common.plsChoose") + t("visitor.dept"), trigger: "blur" }],
  planInAt: [
    { required: true, message: t("common.plsChoose") + t("visitor.planInAt"), trigger: "blur" },
  ],
  planOutAt: [
    { required: true, message: t("common.plsChoose") + t("visitor.planOutAt"), trigger: "blur" },
    { validator: validateDateRange, trigger: "change" },
  ],
});

const statusOptions = ref<OptionType[]>([
  {
    label: t("common.all"),
    value: "-1",
  },
  {
    label: t("visitor.statusOptions.0"),
    value: "0",
  },
  {
    label: t("visitor.statusOptions.1"),
    value: "1",
  },
]);

function handleQuery() {
  loading.value = true;
  VisitorApi.getList(queryParams)
    .then((data) => {
      list.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

function handleOpenDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = t("common.edit");
    VisitorApi.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = t("common.add");
  }
}

function handleSubmit() {
  iFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        VisitorApi.update(formData)
          .then((res) => {
            if (res.data.code === 200) {
              ElMessage.success(res.data.message);
              handleCloseDialog();
              handleResetQuery();
            } else {
              ElMessage.error(res.data.message);
            }
          })
          .finally(() => (loading.value = false));
      } else {
        VisitorApi.add(formData)
          .then((res) => {
            ElMessage.success(res.data.message);
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function handleCloseDialog() {
  dialog.visible = false;

  iFormRef.value.resetFields();
  iFormRef.value.clearValidate();

  formData.id = undefined;
  formData.name = "";
  formData.email = "";
  formData.phone = "";
  formData.status = 1;
  formData.remark = "";
}

function handleDelete(id: number) {
  ElMessageBox.confirm(t("common.confirmDelete"), t("common.warning"), {
    confirmButtonText: t("common.confirm"),
    cancelButtonText: t("common.cancel"),
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      VisitorApi.deleteByIds(id)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            handleResetQuery();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info(t("common.cancelDelete"));
    }
  );
}

const deptOptionsToName = ref<{
  [key: string]: string;
}>();
const deptOptions = ref<OptionType[]>();
function getDeptOptions() {
  DeptAPI.getList({
    pageNum: 1,
    pageSize: 100,
  })
    .then((res) => {
      let idToName: { [key: number]: string } = {};
      let options: OptionType[] = [];
      for (let i = 0; i < res.list.length; i++) {
        let index: number = res.list[i].id;
        idToName[index] = res.list[i].name;
        options.push({
          value: res.list[i].id,
          label: res.list[i].name,
        });
      }
      deptOptionsToName.value = idToName;
      deptOptions.value = options;
    })
    .finally(() => {
      loading.value = false;
    });
}

function getPurposeOptions() {
  VisitPurposeAPI.getOptions({
    pageNum: 1,
    pageSize: 100,
  })
    .then((res) => {
      let idToName: { [key: number]: string } = {};
      let options: OptionType[] = [];
      Object.assign(purposeList, res);
      if (res != null) {
        for (let i = 0; i < purposeList.length; i++) {
          let index: number = purposeList[i].id;
          idToName[index] = purposeList[i].name;
          options.push({
            value: purposeList[i].id,
            label: purposeList[i].name,
          });
        }
      }
      deptOptionsToName.value = idToName;
      purposeOptions.value = options;
    })
    .finally(() => {
      loading.value = false;
    });
}

const share_dialog = reactive({
  title: t("common.share"),
  visible: false,
});

const share_formData = reactive<IShareForm>({
  visitorId: undefined,
  deptId: "",
  purposeId: "",
  planInAt: "",
  planOutAt: "",
});

function handleOpenShareDialog(id: number) {
  share_formData.visitorId = id;
  share_dialog.visible = true;
  share_formData.deptId = "";
  share_formData.purposeId = "";
  share_formData.planInAt = "";
  share_formData.planOutAt = "";
  share_dialog.title = t("visitor.share");
}

function handleSubmitShare() {
  iShareFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      VisitorAPI.sendInvite(share_formData)
        .then((res) => {
          if (res.data.code === 200) {
            ElMessage.success(res.data.message);
            handleCloseShareDialog();
          } else {
            ElMessage.error(res.data.message);
          }
        })
        .finally(() => (loading.value = false));
    }
  });
}

function handleCloseShareDialog() {
  share_dialog.visible = false;
  share_formData.visitorId = undefined;
  share_formData.deptId = 0;
  share_formData.purposeId = 0;
  share_formData.planInAt = "";
  share_formData.planOutAt = "";
}

interface RestaurantItem {
  value: string;
  opUserId: number;
}

const restaurants = ref<RestaurantItem[]>([]);
const querySearch = (queryString: string, cb: any) => {
  const results = queryString
    ? restaurants.value.filter(createFilter(queryString))
    : restaurants.value;
  // call callback function to return suggestions
  cb(results);
};
const createFilter = (queryString: string) => {
  return (restaurant: RestaurantItem) => {
    return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
  };
};
const loadAll = () => {
  const userList: RestaurantItem[] = [];
  VisitorAPI.getVisitorOpUserName().then((res) => {
    if (res != null) {
      res.forEach((user: any) => {
        userList.push({
          value: user.userFullName,
          opUserId: user.userId,
        });
      });
    }
  });
  return userList;
};

const handleSelect = (item: Record<string, any>) => {
  console.log(item.opUserId);
  queryParams.opUserId = item.opUserId;
};

onMounted(() => {
  getPurposeOptions();
  getDeptOptions();
  handleQuery();
  restaurants.value = loadAll();
});
</script>
